#include "pch.h"
#include "seHighscore.h"
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>

using namespace std;

seHighscore::seHighscore()
{
}

void seHighscore::Load()
{
	if (!mImage.LoadFromFile("data/highscore.png")) printf("Blad przy ladowaniu highscore.png");
}

void seHighscore::Init()
{
	mSprite.SetImage(mImage);
	mBoolean = false;
}

void seHighscore::Draw()
{
	mSprite.SetPosition(viewWidth/2 - mImage.GetWidth()/2, viewHeight/2 - mImage.GetHeight()/2); // ustawiamy na srodku
	app.Draw(mSprite);
	
	mNames.SetPosition(viewWidth/2 - mImage.GetWidth()/2 + 90, viewHeight/2 - mImage.GetHeight()/2 + 40);
	mNames.SetSize(21);
	mNames.SetColor(sf::Color(255, 255, 255));
	app.Draw(mNames);

	mScoreValue.SetPosition(viewWidth/2 - mImage.GetWidth()/2 + 460, viewHeight/2 - mImage.GetHeight()/2 + 40);
	mScoreValue.SetSize(21);
	mScoreValue.SetColor(sf::Color(255, 255, 255));
	app.Draw(mScoreValue);
}

void seHighscore::UpdateHighscore(int score)
{
	if(mBoolean)
		return;
	else
		mBoolean = true;

	vector<pair<int, string> > scores;

	fstream plik;
	plik.open("data/highscore.txt",ios::in);
	
	string str;
	
	while(!plik.eof())
	{
		getline(plik,str);

		// split to tokens
		vector<string> tokens;
		string delimiters = ",";

		// Skip delimiters at beginning.
		string::size_type lastPos = str.find_first_not_of(delimiters, 0);
		// Find first "non-delimiter".
		string::size_type pos = str.find_first_of(delimiters, lastPos);

		while (string::npos != pos || string::npos != lastPos)
		{
			// Found a token, add it to the vector.
			tokens.push_back(str.substr(lastPos, pos - lastPos));
			// Skip delimiters.  Note the "not_of"
			lastPos = str.find_first_not_of(delimiters, pos);
			// Find next "non-delimiter"
			pos = str.find_first_of(delimiters, lastPos);
		}
		// splitted
		
		if(tokens.size()) {
			pair<int,string> temp;
			temp.first = -atoi(tokens[0].c_str());
			temp.second = tokens[1];
			scores.push_back(temp);
		}
	}

	plik.close();

	pair<int,string> temp;
	temp.first = -score;
	temp.second = gPlayerName;
	scores.push_back(temp);

	sort(scores.begin(),scores.end());

	ofstream plik2;
	plik2.open("data/highscore.txt");

	string text = "";
	string scoreValue = "";

	char numstr[12];

	for(unsigned int i = 0; i < 13; ++i)
	{
		//cout << scores[i].first << "," << scores[i].second << endl;
		plik2 << -scores[i].first << "," << scores[i].second << endl;
		sprintf(numstr,"%d",-scores[i].first);
		int n = 7 - string(numstr).length();
		text += scores[i].second + "\n\n";
		scoreValue += string(n, ' ') + string(numstr) + "\n\n";
	}
	plik2.close();
	mNames.SetText(text);
	mScoreValue.SetText(scoreValue);
}